package com.tommy.ddp.manager
{
	import com.tommy.ddp.GridDataManager;
	import com.tommy.ddp.definition.AxisConfig;
	import com.tommy.ddp.definition.DDPConfig;
	import com.tommy.ddp.swapHandle.NormalSwapHandler;
	
	import flash.geom.Point;
	
	import starling.events.Event;
	import com.tommy.ddp.box.DdpBox;

	/**
	 * 棋子交换、计算是否可消除的处理
	 * @author hongxuan
	 * 
	 */	
	public class SwapManager
	{
		//private static var targetPoint_1:Point;
		private static var targetPoint_2:Point;
		private static var _orgBox:DdpBox;
		private static var _newBox:DdpBox;
		private static var _dir:int;
		private static var _axis:int;
		
		public function SwapManager()
		{
		}
		/**
		 * 交换棋子
		 * @param orgBox 起始棋子
		 * @param axis 坐标
		 * @param dir 方向
		 * 
		 */		
		public static function swapBox(orgBox:DdpBox,axis:uint,dir:int):void
		{
			_dir = dir;
			_axis = axis;
			
			var newBox:DdpBox;
			if(axis == AxisConfig.X_AXIS)
			{
				newBox = GridDataManager.getBox(orgBox.column+dir,orgBox.row);
			}
			else
			{
				newBox = GridDataManager.getBox(orgBox.column,orgBox.row+dir);
			}
			if(newBox)
			{
				_swapBox(orgBox,newBox);
			}
		}
		
		private static function _swapBox(orgBox:DdpBox,newBox:DdpBox):void
		{
			_orgBox = orgBox;
			_newBox = newBox;
			/*orgBox.scaleX = 1.5;
			newBox.scaleX = 1.5;*/
			//targetPoint_1 = new Point(orgBox.x,orgBox.y);
			targetPoint_2 = new Point(newBox.x,newBox.y);
			
			orgBox.addEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		
		private static function onEnterFrame(event:Event):void
		{
			var vect:Vector.<DdpBox> = new Vector.<DdpBox>();
			
			if(_axis == AxisConfig.X_AXIS)
			{
				_orgBox.x += DDPConfig.SWAP_SPEED*_dir;
				_newBox.x += DDPConfig.SWAP_SPEED*-_dir;
				if(_orgBox.x == targetPoint_2.x)
				{
					_orgBox.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
					trace("step 1 --> swap box");
					changeBoxIndex(_orgBox);
					changeBoxIndex(_newBox);
					//
					//判断两个BOX的类型来决定用哪种swapHandler
					vect.push(_orgBox,_newBox);
					new NormalSwapHandler().execute(vect);
				}
			}
			else
			{
				_orgBox.y += DDPConfig.SWAP_SPEED*_dir;
				_newBox.y += DDPConfig.SWAP_SPEED*-_dir;
				if(_orgBox.y == targetPoint_2.y)
				{
					_orgBox.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
					trace("step 1 --> swap box");
					changeBoxIndex(_orgBox);
					changeBoxIndex(_newBox);
					//
					//判断两个BOX的类型来决定用哪种swapHandler
					vect.push(_orgBox,_newBox);
					new NormalSwapHandler().execute(vect);
				}
			}
		}
		
		/**
		 * 棋子变化后，重新设置列、行信息，并更新HASHMAP里的索引
		 * @param box
		 * 
		 */		
		private static function changeBoxIndex(box:DdpBox):void
		{
			box.column = box.x/DDPConfig.GRID_W;
			box.row = box.y/DDPConfig.GRID_H;
			
			GridDataManager.regBox(box.x/DDPConfig.GRID_W,box.y/DDPConfig.GRID_H,box);
		}
	}
}